package com.wjy.icu.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wjy.icu.common.annotation.RedisEvict;
import com.wjy.icu.common.constant.Constants;
import com.wjy.icu.common.exception.UnauthorizedException;
import com.wjy.icu.common.utils.RedisUtils;
import com.wjy.icu.domain.Icuuser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service("accessTokenService")
public class AccessTokenService {
    @Autowired
    private RedisUtils redis;

    /**
     * 12小时后过期
     */
    private final static long EXPIRE = 12 * 60 * 60;

    private final static String ACCESS_TOKEN = Constants.ACCESS_TOKEN;

    private final static String ACCESS_USERID = Constants.ACCESS_USERID;

    private final static String ACCESS_STAFF = Constants.ACCESS_STAFF;

    public Icuuser queryByToken(String token) {
        return redis.get(ACCESS_TOKEN + token, Icuuser.class);
    }
    @RedisEvict(key = "user_perms", fieldKey = "#petUser.userId")
    public Map<String, Object> createToken(Icuuser user) {
        // 生成token
        String token = IdUtil.fastSimpleUUID();
        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", user.getId());
        map.put("token", token);
        map.put("expire", EXPIRE);
        // expireToken(userId);
        redis.set(ACCESS_TOKEN + token, user, EXPIRE);
        redis.set(ACCESS_USERID + user.getId(), token, EXPIRE);
        return map;
    }

    @RedisEvict(key = "user_perms", fieldKey = "#petUser.userId")
    public Map<String, Object> verifyToken(Icuuser user) {
        //查询token 是否失效
        Map<String, Object> map = new HashMap<String, Object>();
        String token = redis.get(ACCESS_USERID + user.getId());
        if (!StringUtils.isNotBlank(token)){
            // 生成token
            token = IdUtil.fastSimpleUUID();
            // 保存或更新用户token
            map.put("userId", user.getId());
            map.put("token", token);
            map.put("expire", EXPIRE);
            // expireToken(userId);
            redis.set(ACCESS_TOKEN + token, user, EXPIRE);
            redis.set(ACCESS_USERID + user.getId(), token, EXPIRE);
        }else {
            map.put("userId", user.getId());
            map.put("token", token);
            map.put("expire", EXPIRE);
        }
        return map;
    }


    public void expireToken(long userId) {
        String token = redis.get(ACCESS_USERID + userId);
        if (StringUtils.isNotBlank(token)) {
            redis.delete(ACCESS_USERID + userId);
            redis.delete(ACCESS_TOKEN + token);
        }
    }
}